package com.xqx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xqx.mapper.UserMapper;
import com.xqx.pojo.User;
import com.xqx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author：xingquanxiang createTime：2019/10/23 11:25
 * description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public PageInfo<User> findAllByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        //获得与分页相关参数
        PageInfo<User> pageInfo = new PageInfo<User>(userMapper.findAll());
        return pageInfo;
    }

    /**
     * 转账
     *
     * @param payer    付款人
     * @param receiver 收款人
     * @param money
     * @return
     */
    @Override
    public boolean doTransfer(String payer, String receiver, Double money) {
        User userPayer = this.findByName(payer);
        userPayer.setMoney(userPayer.getMoney() - money);

        User userReceiver = this.findByName(receiver);
        userReceiver.setMoney(userReceiver.getMoney() + money);
        int count = 0;
        if (userPayer != null && userReceiver != null) {
            count += userMapper.updateMoneyByName(userPayer);
            count += userMapper.updateMoneyByName(userReceiver);
        }
        return count == 2;
    }

    @Override
    public User findByName(String name) {
        User user = new User();
        user.setName(name);
        return userMapper.findByCondition(user);
    }

    @Override
    public User findByCondition(User user) {
        return userMapper.findByCondition(user);
    }

    @Override
    public User doSave(User user) {
        userMapper.save(user);
        return user;
    }


    @Override
    public User findById(int id) {
        User user = new User();
        user.setId(id);
        return userMapper.findByCondition(user);
    }

    @Override
    public List<User> findLikeName(String name) {
        return userMapper.findLikeName(name);
    }

    @Override
    public int doDelById(int[] ids) {
        return userMapper.delById(ids);
    }
}
